package org.sagitta.httprpc.hessian.adaptor;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sagitta.httprpc.ResponseMashaller;
import org.sagitta.httprpc.exception.RPCException;
import org.sagitta.httprpc.message.Response;

import com.caucho.hessian.io.AbstractHessianOutput;
import com.caucho.hessian.io.Hessian2Output;
import com.caucho.hessian.io.SerializerFactory;

public class HessianResponseMashaller implements ResponseMashaller {
	private static final Log log = LogFactory.getLog(HessianResponseMashaller.class);
	private SerializerFactory serializerFactory;

	@Override
	public byte[] marshal(Response response) throws RPCException {
		try {
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			AbstractHessianOutput out = new Hessian2Output(os);
			out.setSerializerFactory(serializerFactory);
			out.startReply();
			out.writeObject(response);
			out.completeReply();
			out.flush();
			os.flush();
			out.close();
			byte[] b = os.toByteArray();
			if (log.isDebugEnabled()) {
				log.debug(HessianUtil.byteArrayToHexString(b));
			}
			return b;
		} catch (IOException e) {
			e.printStackTrace();
			throw new RPCException(RPCException.RESPONSEMASHLLERROR);
		}
	}

	@Override
	public void marshal(Response response, OutputStream stream) throws RPCException {
		try {
			AbstractHessianOutput out = new Hessian2Output(stream);
			out.setSerializerFactory(serializerFactory);
			out.startReply();
			out.writeObject(response);
			out.completeReply();
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new RPCException(RPCException.RESPONSEMASHLLERROR);
		}
	}

	public SerializerFactory getSerializerFactory() {
		return serializerFactory;
	}

	public void setSerializerFactory(SerializerFactory serializerFactory) {
		this.serializerFactory = serializerFactory;
	}

}
